package cn.net.dckj.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by martin on 2017/7/2.
 */
public class HttpClientUtil {

    public static CloseableHttpClient httpClient = null;
    public static HttpClientContext context = null;
    public static CookieStore cookieStore = null;
    public static RequestConfig requestConfig = null;

    static {
        init();
    }

    private static void init() {
        context = HttpClientContext.create();
        cookieStore = new BasicCookieStore();
        // 配置超时时间（连接服务端超时1秒，请求数据返回超时2秒）
        requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
                .setConnectionRequestTimeout(60000).build();
        // 设置默认跳转以及存储cookie
        httpClient = HttpClientBuilder.create()
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
                .setDefaultCookieStore(cookieStore).build();
    }

    public static Map<String, Object> post(String url, Map<String, Object> params) {
        return post(url, params, null, null);
    }

    public static Map<String, String> post1(String url, Map<String, Object> params) {
        Map<String, String> rtn = new HashMap<String, String>();
        Map<String, Object> map = post(url, params, null, null);
        Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            rtn.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return rtn;
    }

    public static Map<String, Object> post(String url, Map<String, Object> params, String sessionId, String token_id) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            if (sessionId != null && !sessionId.isEmpty()) {
                httpPost.addHeader("Cookie", "ccjzxyxt.session.id=" + sessionId);
            }
            if (token_id != null && !token_id.isEmpty()) {
                httpPost.addHeader("token_id", token_id);
            }
            StringEntity entity = new StringEntity(SerializeUtil.serializeJson(params), "utf-8");//解决中文乱码问题
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost, context);
            HttpEntity httpEntity = response.getEntity();
            // do something useful with the response body
            result = EntityUtils.toString(httpEntity, "UTF-8");
            EntityUtils.consume(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return formatResult(result);
    }

    public static Map<String, Object> get(String url) {
        return get(url, null, null);
    }

    public static Map<String, Object> get(String url, String sessionId, String token_id) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            if (sessionId != null && !sessionId.isEmpty()) {
                httpGet.addHeader("Cookie", "ccjzwxyxt.session.id=" + sessionId);
            }
            if (token_id != null && !token_id.isEmpty()) {
                httpGet.addHeader("token_id", token_id);
            }
            response = httpClient.execute(httpGet, context);
            HttpEntity httpEntity = response.getEntity();
            // do something useful with the response body
            result = EntityUtils.toString(httpEntity, "UTF-8");
            // and ensure it is fully consumed
            EntityUtils.consume(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return formatResult(result);
    }

    private static Map formatResult(String result) {
        Map rtn = SerializeUtil.json2Map(result);
        return rtn;
    }
}
